<template>
  <div id="login">
    <img class="background" src="../../assets/background.jpg" alt="background Image" />
    <div class="login_from">
      <img class="Logo" src="../../assets/Login_Logo.jpg" alt="logo Image" />
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginForm"
        label-width="70px"
        label-position="top"
      >
        <el-form-item label="用户名:" prop="user">
          <el-input
            v-model="loginForm.user"
            placeholder="请输入用户名"
            maxlength="20"
            minlength="0"
            clearable
            autofocus
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            type="password"
            maxlength="20"
            minlength="6"
            clearable
            show-password
            @keyup.enter="login"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 40%; margin-left: 10%"
            round
            @click="register"
            :loading="registerLoging"
            >注册</el-button
          >
          <el-button
            type="primary"
            style="width: 40%; margin-left: 5%"
            round
            @click="login"
            :loading="loginLoading"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
      测试账号：test<br />
      测试密码：123456
    </div>
  </div>
</template>

<script>
import { LoginInterface } from "../../api/login/index";
export default {
  mounted() {
    //绑定事件
    window.addEventListener("keydown", this.keyDown);
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("账号不能为空"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不少于 6 位"));
      } else if (value.length > 20) {
        callback(new Error("密码长度不大于 20 位"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        user: "",
        password: "",
      },
      rules: {
        user: [
          {
            required: true,
            trigger: "blur",
            validator: validateUsername,
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword,
          },
        ],
      },
      loginLoading: false,
      registerLoging: false,
    };
  },
  methods: {
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        this.login();
      }
    },
    /**
     * 点击注册按钮时触发
     */
    register() {
      this.registerLoading = true;
      //  提示
      this.$notify({
        /* 指定消息的标题 */
        title: "登录",
        /* 指定消息的内容 */
        message: "正在跳转到注册页面，请稍候...",
        /* 指定消息出现的位置 */
        position: "top-right",
        /* 指定消息的类型 */
        type: "success",
        /* 持续两秒钟 */
        duration: 2 * 1000,
      });

      //  跳转到注册页面
      window.setTimeout(() => {
        this.$router.push({
          name: "注册",
        });

        //  取消按钮加载状态
        this.registerLoading = false;
      }, 1000);
    },
    /**
     * 点击登录按钮时触发
     */
    login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          //  表单验证通过（输入的数据符合要求）
          var user = {
            name: this.loginForm.user,
            password: this.loginForm.password,
          };
          //  按钮处于加载状态
          this.loginLoading = true;
          await LoginInterface(user).then(
            (res) => {
              if (res.token !== null) {
                this.$store.commit("setToken", res.token);
                this.$store.commit("setUserInfo", JSON.stringify(res));

                //  标记为已经登录的状态
                this.$store.state.isLogin = true;
                sessionStorage.setItem("isLogin", true);

                window.setTimeout(() => {
                  //  提示
                  this.$notify({
                    /* 指定消息的标题 */
                    title: "登录",
                    /* 指定消息的内容 */
                    message: "登录成功，欢迎【 " + this.loginForm.user + "】光临！！",
                    /* 指定消息出现的位置 */
                    position: "top-right",
                    /* 指定消息的类型 */
                    type: "success",
                    /* 持续两秒钟 */
                    duration: 2 * 1000,
                  });

                  //  跳转到首页
                  this.$router.push({
                    name: "首页",
                    params: { userID: res.id },
                  });

                  //  取消按钮加载状态
                  this.loginLoading = false;
                }, 100);
              }
            },
            (err) => {
              console.log(err);
            }
          );
        }
      });
      this.loginLoading = false;
    },
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
};
</script>

<style>
.background {
  width: 100%;
  top: 0;
  left: 0;
  height: 770px;
  z-index: -9999;
  position: absolute;
}

.login_from {
  margin: 130px 40%;
  padding: 30px;
  width: 300px;
  border-radius: 20px;
  background-color: white;
  opacity: 0.9;
}

.Logo {
  width: 100px;
  height: 100px;
  border: 1px solid gainsboro;
  border-radius: 50%;
  margin-left: 30%;
  margin-top: -80px;
  margin-bottom: 30px;
}
</style>
